import json
import requests
import os

import down_book
import AES_decryption

bookList_ = os.path.abspath('bookList.txt')
dict_book = {}


# 手动构造加密后的url（因为所有代码都是服务处理加密url的，不想改了）
def encrypt_url(list_):
    iv = '{"words": [825373492, 892745528, 959459634, 859059510], "sigBytes": 16}'

    text = f'bookId={list_[0]}&eisbn={list_[1]}'
    data = {
        'plaintext': bytes(text, 'utf-8'),
        'iv': b'1234567890123456',
        'key': b'1111111111111111'
    }
    text = AES_decryption.AES_encrypt(data)

    encrypted_str = f'{{"encrypt":"{text}","iv":{iv}}}'
    encrypted_str = AES_decryption.base64_encrypt(bytes(encrypted_str, 'utf-8'))

    return encrypted_str


# 获取书本信息，或保存到本地
def book_list():
    print('更新书本信息中')
    # 从本地文件获取书本信息
    content = None
    if not os.path.exists(bookList_):
        with open(bookList_, 'w', encoding='utf-8') as f:
            pass
    else:
        with open(bookList_, 'r', encoding='utf-8') as f:
            content = f.readline().strip()
        try:
            content = content.split(',')
        except:
            content = None

    # 从网站获取书本信息，并比对网站有无更新
    url = 'https://zengzhi.ipmph.com/zhbooks/zzfw_web?command=bookList'
    json_dicts = {"catalogId": "15238", "pageSize": 5, "pageIndex": 1, "keyWord": ""}

    params = {'json': json.dumps(json_dicts)}
    response = requests.get(url, params=params)
    data = response.json()
    totalPage = data['data']['totalPage']
    bookList = data['data']['bookList']
    for item in bookList:
        title = item['title']
        eisbn = item['eisbn']
        id_ = item['id']
        if content and title == content[0]:
            return

        en_url = encrypt_url([id_, eisbn])
        with open(bookList_, 'a', encoding='utf-8') as f:
            f.write(f'{title},{en_url}\n')

    for pageIndex in range(2, totalPage + 1):
        json_dicts['pageIndex'] = pageIndex
        params = {'json': json.dumps(json_dicts)}
        response = requests.get(url, params=params)
        data = response.json()
        bookList = data['data']['bookList']
        for item in bookList:
            title = item['title']
            eisbn = item['eisbn']
            id_ = item['id']
            en_url = encrypt_url([id_, eisbn])
            with open(bookList_, 'a', encoding='utf-8') as f:
                f.write(f'{title},{en_url}\n')


# 读取本地文件，获取信息（字典形式）
def book_dict():
    global dict_book
    with open(bookList_, 'r', encoding='utf-8') as f:
        content = f.read().split('\n')
    for item in content:
        item = item.strip()
        if len(item) > 4:
            item = item.split(',')
            dict_book[item[0]] = 'https://zengzhi.ipmph.com/#/bookDetail?' + item[1]
        else:
            pass
    return


# 搜索下载功能
def find_book():
    def fuzzy_search_dict_keys(d, pattern_):
        matching_keys_ = [key for key in d if pattern_ in key]
        return matching_keys_

    print('若要退出程序：请按下exit')
    while True:
        pattern = input('\033[92m输入你要下载哪本书（书名，完整版的书名）：\033[0m').strip()
        if pattern.strip() == 'exit':
            return
        matching_keys = fuzzy_search_dict_keys(dict_book, pattern)
        if len(matching_keys) == 0:
            print('无此书')
            continue
        elif len(matching_keys) == 1:
            data = [matching_keys[0], dict_book[matching_keys[0]]]
        else:
            length = len(matching_keys)
            for i in range(length):
                print(f'{i + 1},{matching_keys[i]}')
            index = input(f'\033[92m输入序号选择下载那本书({1}-{length})：\033[0m')
            try:
                index = int(index)
                print(f'下载：{matching_keys[index - 1]}')
                data = [matching_keys[index - 1], dict_book[matching_keys[index - 1]]]
            except:
                print('输入有误')
                continue

        flag = input('\033[92m是否下载（Y/N）：\033[0m')
        # if not data:
        #     flag = 'n'
        if flag == 'Y' or flag == 'y':
            try:
                down_book.strat_download_book_pdf(data[1])
            except Exception as e:
                print(e)
                print('出现未知错误，暂时无法下载')


book_list()
book_dict()
find_book()
